import { useCache, CACHE_KEY } from '@/hooks/web/useCache'
import { TokenType } from '@/api/login/types'
import { decrypt, encrypt } from '@/utils/jsencrypt'

const { wsCache } = useCache()

const AccessTokenKey = 'ACCESS_TOKEN'
const RefreshTokenKey = 'REFRESH_TOKEN'

// 获取token
export const getAccessToken = () => {
  // 此处与TokenKey相同，此写法解决初始化时Cookies中不存在TokenKey报错
  return wsCache.get(AccessTokenKey) ? wsCache.get(AccessTokenKey) : wsCache.get('ACCESS_TOKEN')
}

// 刷新token
export const getRefreshToken = () => {
  return wsCache.get(RefreshTokenKey)
}

// 设置token
export const setToken = (token: TokenType) => {
  wsCache.set(RefreshTokenKey, token.refreshToken)
  wsCache.set(AccessTokenKey, token.accessToken)
}

// 设置用户ID
export const setUserId = (data) => {
  wsCache.set('userId', data)
}
// 获取用户ID
export const getUserId = () => {
  return wsCache.get('userId')
}

// 删除token
export const removeToken = () => {
  wsCache.delete(AccessTokenKey)
  wsCache.delete(RefreshTokenKey)
}
// 设置是否为sso登录
export const setSSOFlag = (data) => {
  wsCache.set('sso', data)
}
// 获取是否为sso登录
export const getSSOFlag = () => {
  return wsCache.get('sso')
}
// 设置是否为sso退出
export const setSSOQuit = (data) => {
  wsCache.set('ssoQuit', data)
}
// 获取是否为sso退出
export const getSSOQuit = () => {
  return wsCache.get('ssoQuit')
}
// 获取选中项目ID
export const getProjectId = () => {
  return wsCache.get('projectId')
}
// 设置鸿渐token
export const setHJToken = (data) => {
  wsCache.set('HJToken', data)
}
// 获取鸿渐token
export const getHJToken = () => {
  return wsCache.get('HJToken')
}
// 设置ssotoken
export const setssoToken = (data) => {
  wsCache.set('ssoToken', data)
}
// 获取ssotoken
export const getssoToken = () => {
  return wsCache.get('ssoToken')
}
/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return 'Bearer ' + token
}
// ========== 账号相关 ==========

export type LoginFormType = {
  tenantName?: string
  username: string
  password: string
  rememberMe: boolean
}

export const getLoginForm = () => {
  const loginForm: LoginFormType = wsCache.get(CACHE_KEY.LoginForm)
  if (loginForm) {
    loginForm.password = decrypt(loginForm.password) as string
  }
  return loginForm
}

export const setLoginForm = (loginForm: LoginFormType) => {
  loginForm.password = encrypt(loginForm.password) as string
  wsCache.set(CACHE_KEY.LoginForm, loginForm, { exp: 30 * 24 * 60 * 60 })
}

export const removeLoginForm = () => {
  wsCache.delete(CACHE_KEY.LoginForm)
}

export const setUserInfo = (userInfo) => {
  wsCache.set(CACHE_KEY.USER, userInfo)
}
// ========== 租户相关 ==========

export const getTenantId = () => {
  return wsCache.get(CACHE_KEY.TenantId)
}

export const setTenantId = (data) => {
  wsCache.set(CACHE_KEY.TenantId, data)
}
